﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;
using BW.Mes.WinForms.BasicData;
using Newtonsoft.Json.Linq;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateBomForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private readonly long _editId;
        private BindingList<BomSparepartViewModel> spareparts = new BindingList<BomSparepartViewModel>();
        public UpdateBomForm(BomForm.BomModel model)
        {
            InitializeComponent();
            gridView1.OptionsBehavior.AutoPopulateColumns = false; // 关闭自动生成列，只显示手动添加的列
            _editId = model.Id;
            this.Load += UpdateBomForm_Load;
            comboBoxEditType.Properties.Items.Clear();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "成品", "半成品", "原材料", "其他" });
            comboBoxEditType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBoxEditType.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Flat;
            comboBoxEditType.Properties.Appearance.BorderColor = System.Drawing.Color.LightGray;
            comboBoxEditType.Properties.Appearance.Options.UseBorderColor = true;
            comboBoxEditType.Properties.Appearance.BackColor = System.Drawing.Color.White;
            comboBoxEditType.Properties.Appearance.Options.UseBackColor = true;
            comboBoxEditType.Properties.NullText = "请选择类型";
            // 主表反填
            textEditCode.Text = model.BomCode;
            textEditName.Text = model.BomName;
            textEditVersion.Text = model.Version;
            comboBoxEditType.Text = model.BomType;
            textEditNumber.Text = model.BomNumber;
            textEditMsg.Text = model.BomMsg;
            textEditMoney.Text = model.BomMoney;
            // 只绑定一次数据源
            gridControl1.DataSource = spareparts;
            SetupSparepartsGridDev();
            btnRemoveSparepart.Click += btnRemoveSparepart_Click;
        }
        private async void UpdateBomForm_Load(object sender, EventArgs e)
        {
            await LoadSpareparts();
        }
        private async Task LoadSpareparts()
        {
            var client = new HttpClient();
            var response = await client.GetAsync($"{_apiBaseUrl}/T2/Bom/GetBomSparepart");
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
                var listToken = obj["pageDatas"] ?? obj["data"] ?? obj["result"];
                var allSpareparts = listToken != null
                    ? JsonConvert.DeserializeObject<List<BomSparepartViewModel>>(listToken.ToString())
                    : new List<BomSparepartViewModel>();
                spareparts.Clear();
                foreach (var item in allSpareparts)
                {
                    spareparts.Add(item);
                }
                // 不再重新赋值DataSource和Columns.Clear()
                // gridControl1.DataSource = null;
                // gridView1.Columns.Clear();
                // gridControl1.DataSource = spareparts;
                SetupSparepartsGridDev();
            }
        }
        private void SetupSparepartsGridDev()
        {
            gridView1.Columns.Clear();
            gridView1.Columns.AddVisible("Id", "Id");
            gridView1.Columns.AddVisible("ParentId", "Parent Id");
            gridView1.Columns.AddVisible("ProductCode", "Product Code");
            gridView1.Columns.AddVisible("ProductName", "Product Name");
            gridView1.Columns.AddVisible("Specification", "Specification");
            gridView1.Columns.AddVisible("Unit", "Unit");
            gridView1.Columns.AddVisible("Spend", "Spend");
            gridView1.Columns.AddVisible("NNumber", "NNumber").OptionsColumn.AllowEdit = true;
            gridView1.Columns.AddVisible("BomBfb", "Bom Bfb").OptionsColumn.AllowEdit = true;
            gridView1.OptionsBehavior.Editable = true;
            // 斑马纹美化（极浅粉色）
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#ffeaf4");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#fff6fb");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            // 表头同色
            gridView1.Appearance.HeaderPanel.BackColor = ColorTranslator.FromHtml("#ffeaf4");
            gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
            // 选中行不覆盖背景色
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;
            // 禁用皮肤影响
            gridView1.Appearance.Row.BackColor = Color.Empty;
            gridView1.Appearance.Row.Options.UseBackColor = false;
        }
        private void btnAddSparepart_Click(object sender, EventArgs e)
        {
            var part = new BomSparepartViewModel
            {
                NNumber = 0,
                BomBfb = string.Empty,
                CreatedAt = DateTime.Now
            };
            spareparts.Add(part);
        }
        private void btnRemoveSparepart_Click(object sender, EventArgs e)
        {
            var row = gridView1.GetFocusedRow() as BomSparepartViewModel;
            if (row != null)
            {
                spareparts.Remove(row);
            }
        }
        private void btnEditSparepart_Click(object sender, EventArgs e)
        {
            // 这里可以实现选中行的编辑逻辑，或直接在Grid中编辑
            // 如无特殊弹窗需求，可留空或提示
        }
        private async void btnOK_Click(object sender, EventArgs e)
        {
            gridView1.PostEditor();
            gridView1.UpdateCurrentRow();
            // 调试：弹窗显示spareparts内容
            // MessageBox.Show(string.Join("\n", spareparts.Select(x => $"{x.ProductCode} 数量={x.NNumber} 损耗率={x.BomBfb}")));
            var model = new
            {
                Id = _editId,
                BomCode = textEditCode.Text,
                BomName = textEditName.Text,
                Version = textEditVersion.Text,
                BomType = comboBoxEditType.Text,
                BomNumber = textEditNumber.Text,
                BomMoney = textEditMoney.Text,
                BomMsg = textEditMsg.Text,
                UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
            };
            string jsonData = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.PutAsync($"{_apiBaseUrl}/T2/Bom/UpdateBom", content);
            if (response.IsSuccessStatusCode)
            {
                // 保存配件，确保每个配件都同步到后端
                foreach (var part in spareparts)
                {
                    part.UpdatedAt = DateTime.Now;
                    var partToPost = new
                    {
                        Product_id = part.Id,
                        Spend = part.Spend,
                        NNumber = part.NNumber,
                        BomBfb = part.BomBfb,
                        ParentId = 0, // 如有父级ID请赋值
                        CreatedBy = part.CreatedBy,
                        CreatedAt = part.CreatedAt,
                        UpdatedAt = part.UpdatedAt
                    };
                    string partJson = JsonConvert.SerializeObject(partToPost);
                    var partContent = new StringContent(partJson, Encoding.UTF8, "application/json");
                    var partResponse = await client.PostAsync($"{_apiBaseUrl}/T2/Bom/UpdateBomSparepart", partContent);
                    // 可选：检查partResponse.IsSuccessStatusCode
                }
                XtraMessageBox.Show("修改成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                XtraMessageBox.Show("修改失败！");
            }
        }
        private void btnOK_Click_1(object sender, EventArgs e)
        {
            btnOK_Click(sender, e);
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnUpdateSparepart_Click_1(object sender, EventArgs e)
        {

        }

        private void UpdateBomForm_Load_1(object sender, EventArgs e)
        {

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }
    }

    public class BomSparepartResponse
    {
        public int totalCount { get; set; }
        public List<BomSparepartViewModel> pageDatas { get; set; }
        public string message { get; set; }
        public object data { get; set; }
        public int code { get; set; }
    }
}